package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanReportQueryRequest;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportAuditStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.features.SalesPlanFeatures;
import com.alibaba.citrus.cr.sales.plan.repository.PlatformEnhanceRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.cr.sales.plan.repository.response.EmployeeRoleResponse;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanReportSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.report.SalesPlanReportQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.OrganizationSelectRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQuerySalePlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.api.organizationquery.dto.GetOrganizationByTypeRequest;
import com.epoch.app.crplatformenhance.api.organizationquery.dto.GetOrganizationByTypeResponse;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.enums.RoleCodeEnum;
import com.epoch.app.crplatformenhance.sdo.EmployeeSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-09-15 22:08
 */
@Service
public class SalesPlanQueryServiceImpl implements SalesPlanQueryService {

    private static final Log log = Log.getLogger(SalesPlanQueryServiceImpl.class);

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanReportQueryService salesPlanReportQueryService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private PlatformEnhanceRepository platformEnhanceRepository;

    @Resource
    private OrganizationQueryService organizationQueryService;


    @Override
    @FacadeInvoker
    public Result<SalesPlanSDO> getSalesPlan(QuerySalesPlanRequest querySalesPlanRequest) {
        if (querySalesPlanRequest.getBizType() != null) {
            if (querySalesPlanRequest.getBizType() < SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                querySalesPlanRequest.setBizType(null);
                querySalesPlanRequest.setBizId(null);
            }
        }
        SalesPlanSDO salesPlanSDO = salesPlanRepository.load(querySalesPlanRequest);
        if (Objects.nonNull(salesPlanSDO)) {
            enichSalesPlanSDO(salesPlanSDO, querySalesPlanRequest);
        }
        return Result.success(salesPlanSDO);
    }

    private void enichSalesPlanSDO(SalesPlanSDO salesPlanSDO, QuerySalesPlanRequest querySalesPlanRequest) {
        //features
        if (StringUtil.isNotEmpty(salesPlanSDO.getFeatures())) {
            SalesPlanFeatures salesPlanFeatures = salesPlanRepository.convertSalesPlanFeatures(salesPlanSDO.getFeatures());
            BeanUtils.copyProperties(salesPlanFeatures, salesPlanSDO);
        }
        //状态
        salesPlanSDO.setStatusDesc(SalesPlanStatusEnum.getDesc(salesPlanSDO.getStatus()));
        //计划时间格式
        if (StringUtil.isNotEmpty(salesPlanSDO.getPlanTime())) {
            //返回数据是时间戳,对时间戳做处理
            String planTime = DateUtils.stampToDate(salesPlanSDO.getPlanTime());
            try {
                //2021年10月份
                salesPlanSDO.setFormatPlanTime(DateUtils.formatPlanTime(planTime));
                //2021-10-01 00:00:00
                salesPlanSDO.setPlanTime(planTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //是否能编辑三旬均衡
        salesPlanSDO.setIsAllowProprtion(true);
        if(SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus())){
            Map<Long, com.epoch.app.bcorder.model.dto.SalesPlanSDO> planDetailCountMap = salesPlanLineRepository.statisticalPlanDetailCount(Lists.newArrayList(salesPlanSDO.getId()));
            if(planDetailCountMap.get(salesPlanSDO.getId()) == null){
                salesPlanSDO.setIsAllowProprtion(false);
            }
        }

        // 审批状态
        if (querySalesPlanRequest.getBizType() != null && StringUtil.isNotEmpty(querySalesPlanRequest.getBizId())) {
            SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(querySalesPlanRequest.getBizType());
            if (byOrganizationType == null) {
                throw new FacadeException(ErrorMessage.code("OTS-02-002-02-15-007"));
            }
            SalesPlanReportQueryRequest salesPlanReportQueryRequest = new SalesPlanReportQueryRequest();
            salesPlanReportQueryRequest.setModelId(salesPlanSDO.getId().toString());
            salesPlanReportQueryRequest.setModelType(salesPlanSDO.getModel());
            salesPlanReportQueryRequest.setBizId(querySalesPlanRequest.getBizId());
            salesPlanReportQueryRequest.setBizType(byOrganizationType.getBizType());
            Result<SalesPlanReportSDO> salesPlanReportSDOResult = salesPlanReportQueryService.querySalesPlanReport(salesPlanReportQueryRequest);
            SalesPlanReportSDO salesPlanReportSDO = salesPlanReportSDOResult.getResult();
            if (Objects.nonNull(salesPlanReportSDO)) {
                salesPlanSDO.setAuditStatus(salesPlanReportSDO.getAuditStatus());
                salesPlanSDO.setAuditStatusName(SalesPlanReportAuditStatusEnum.of(salesPlanReportSDOResult.getResult().getAuditStatus()).getDesc());
                salesPlanSDO.setReportStatus(salesPlanReportSDO.getStatus());
                salesPlanSDO.setReportStatusName(SalesPlanReportStatusEnum.of(salesPlanReportSDOResult.getResult().getStatus()).getDesc());
                salesPlanSDO.setReportOrderId(salesPlanReportSDO.getId());
                salesPlanSDO.setIsAllowEdit(isAllowEdit(salesPlanReportSDO, querySalesPlanRequest));// 审批中，判断明细是否能被审批
            } else {
                salesPlanSDO.setAuditStatus(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode());
                salesPlanSDO.setAuditStatusName(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getDesc());
                salesPlanSDO.setReportStatus(SalesPlanReportStatusEnum.TO_REPORT.getCode());
                salesPlanSDO.setReportStatusName(SalesPlanReportStatusEnum.TO_REPORT.getDesc());
                salesPlanSDO.setIsAllowEdit(true);
            }
        }
    }

    private boolean isAllowEdit(SalesPlanReportSDO salesPlanReportSDO, QuerySalesPlanRequest querySalesPlanRequest) {
        // 非审批中的默认true
        if (!SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode().equals(salesPlanReportSDO.getAuditStatus())) {
            return true;
        }
        // 提报人
        String reportEmployeeId = salesPlanReportSDO.getReportEmployeeId();
        String operatorId = querySalesPlanRequest.getOperatorId();
        if (StringUtils.isBlank(operatorId)) {
            return true;
        }
        // 提报人和登录人一致，直接不可编辑
        if (Objects.equals(reportEmployeeId, operatorId)) {
            return false;
        }
        // 需要判断提报人和登录人是不是同一个角色
        List<EmployeeSDO> employeeSDOList = platformEnhanceRepository.getEmployeeList(Lists.newArrayList(reportEmployeeId, operatorId));
        if (CollectionUtils.isEmpty(employeeSDOList) || employeeSDOList.size() != 2) {
            return true;
        }
        //  角色查询
        List<EmployeeRoleResponse> reportRoles = platformEnhanceRepository.getEmployeeRoleListById(reportEmployeeId, 1);
        if (CollectionUtils.isEmpty(reportRoles)) {
            return true;
        }
        List<EmployeeRoleResponse> operatorRoles = platformEnhanceRepository.getEmployeeRoleListById(operatorId, 1);
        if (CollectionUtils.isEmpty(operatorRoles)) {
            return true;
        }
        List<String> reportCodes = reportRoles.stream().map(EmployeeRoleResponse::getCode).collect(Collectors.toList());
        List<String> operatorCodes = operatorRoles.stream().map(EmployeeRoleResponse::getCode).collect(Collectors.toList());
        List<String> shareRoleList = reportCodes.stream().filter(operatorCodes::contains).collect(Collectors.toList());
        // 同一角色不允许编辑
        return CollectionUtils.isEmpty(shareRoleList);
    }

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanSDO>>> pageQuerySalesPlanList(PageQuerySalePlanRequest pageQuerySalePlanRequest) {
        if (pageQuerySalePlanRequest.getBizType() != null) {
            List<String> orgIds = null;
            if (CollectionUtils.isNotEmpty(pageQuerySalePlanRequest.getOrgBusinessUnitCodes())){
                List<String> orgBusinessUnitCodeList = pageQuerySalePlanRequest.getOrgBusinessUnitCodes();
                // 传入业务code 获取ID
                BaselineGetOrganizationByOutCodes2Response baselineGetOrganizationByOutCodes2Response =
                        baseDataService.baselineGetOrganizationByOutCodes2(BaselineGetOrganizationByOutCodes2Request.builder().outCodes(orgBusinessUnitCodeList).build());
                orgIds = baselineGetOrganizationByOutCodes2Response.getResult().stream().map(e -> e.getId()).collect(Collectors.toList());
            }
            if (StringUtil.isBlank(pageQuerySalePlanRequest.getOrgBusinessUnitCode())) {
                //查询登录人所属业务单元
                OrganizationSelectRequest organizationSelectRequest = new OrganizationSelectRequest();
                organizationSelectRequest.setRelatedOrganizationType(pageQuerySalePlanRequest.getRelatedOrganizationType());
                organizationSelectRequest.setRelatedOrganizationId(pageQuerySalePlanRequest.getRelatedOrganizationId());
                Result<List<OrganizationSDO>> listResult = organizationSelect(organizationSelectRequest);
                if (CollectionUtils.isNotEmpty(orgIds) && CollectionUtils.isNotEmpty(orgIds)){
                    List<String> orgBusinessUnitCodes = listResult.getResult().stream().map(OrganizationSDO::getId).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                    orgIds.retainAll(orgBusinessUnitCodes);
                    pageQuerySalePlanRequest.setOrgBusinessUnitCodes(orgIds);
                }else {
                    if (CollectionUtils.isNotEmpty(pageQuerySalePlanRequest.getOrgBusinessUnitCodes())){
                        pageQuerySalePlanRequest.setOrgBusinessUnitCode("failed");
                    }else {
                        List<String> orgBusinessUnitCodes = listResult.getResult().stream().map(OrganizationSDO::getId).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                        pageQuerySalePlanRequest.setOrgBusinessUnitCodes(orgBusinessUnitCodes);
                    }
                }
            }else{
                ArrayList<String> orgBusinessUnitCodes = new ArrayList<String>();
                orgBusinessUnitCodes.add(pageQuerySalePlanRequest.getOrgBusinessUnitCode());
                if (CollectionUtils.isNotEmpty(pageQuerySalePlanRequest.getOrgBusinessUnitCodes())){
                    orgIds.retainAll(orgBusinessUnitCodes);
                    pageQuerySalePlanRequest.setOrgBusinessUnitCodes(orgIds);
                    if (CollectionUtils.isEmpty(orgIds)){
                        // 特殊字符，目的是查不出数据
                        pageQuerySalePlanRequest.setOrgBusinessUnitCode("failed");
                    }
                }
            }
            if (pageQuerySalePlanRequest.getBizType() < SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                pageQuerySalePlanRequest.setBizType(null);
                pageQuerySalePlanRequest.setBizId(null);
            }
        }

        pageQuerySalePlanRequest.setDir("planTime");
        pageQuerySalePlanRequest.setAsc(false);
        PageResult<List<SalesPlanSDO>> listPageResult = salesPlanRepository.pageQuery(pageQuerySalePlanRequest);
        if (null != listPageResult && CollectionUtils.isNotEmpty(listPageResult.getContent())) {
            // 获取登录人的状态信息
            GetLoginEmployeeInfoResponse employeeInfoResponse = baseDataService.getLoginEmployeeInfo();
            if (null == employeeInfoResponse || CollectionUtils.isEmpty(employeeInfoResponse.getRoles())) {
                log.error("登录员工未配置角色");
                return Result.success(null);
            }
            pageResultConverter(listPageResult, pageQuerySalePlanRequest, employeeInfoResponse.getRoles());
        }
        return Result.success(listPageResult);
    }

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanSDO>>> pageQuerySalesPlanListInValid(PageQuerySalePlanRequest pageQuerySalePlanRequest) {
        if (pageQuerySalePlanRequest.getBizType() != null) {
            if (StringUtil.isBlank(pageQuerySalePlanRequest.getOrgBusinessUnitCode())) {
                //查询登录人所属业务单元
                OrganizationSelectRequest organizationSelectRequest = new OrganizationSelectRequest();
                organizationSelectRequest.setRelatedOrganizationType(pageQuerySalePlanRequest.getRelatedOrganizationType());
                organizationSelectRequest.setRelatedOrganizationId(pageQuerySalePlanRequest.getRelatedOrganizationId());
                Result<List<OrganizationSDO>> listResult = organizationSelect(organizationSelectRequest);
                if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                    List<String> orgBusinessUnitCodes = listResult.getResult().stream().map(OrganizationSDO::getId).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                    pageQuerySalePlanRequest.setOrgBusinessUnitCodes(orgBusinessUnitCodes);
                }
            }
            if (pageQuerySalePlanRequest.getBizType() < SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                pageQuerySalePlanRequest.setBizType(null);
                pageQuerySalePlanRequest.setBizId(null);
            }
        }
        pageQuerySalePlanRequest.setDir("planTime");
        pageQuerySalePlanRequest.setAsc(false);
        PageResult<List<SalesPlanSDO>> listPageResult = salesPlanRepository.pageQuery(pageQuerySalePlanRequest);
        if (null != listPageResult && CollectionUtils.isNotEmpty(listPageResult.getContent())) {
            // 获取登录人的状态信息
            pageResultConverter(listPageResult, pageQuerySalePlanRequest, null);
        }
        return Result.success(listPageResult);
    }

    private void pageResultConverter(PageResult<List<SalesPlanSDO>> listPageResult, PageQuerySalePlanRequest pageQuerySalePlanRequest, List<RoleSDO> roles) {
        if (null == listPageResult || listPageResult.getTotal() < 1) {
            return;
        }
//        List<Long> planIdList = listPageResult.getContent().stream().map(SalesPlanSDO::getId).collect(Collectors.toList());
//        Map<Long, com.epoch.app.bcorder.model.dto.SalesPlanSDO> planDetailCountMap = salesPlanLineRepository.statisticalPlanDetailCount(planIdList);
        listPageResult.getContent().forEach(salesPlanSDO -> {
            // features
            if (StringUtil.isNotEmpty(salesPlanSDO.getFeatures())) {
                SalesPlanFeatures salesPlanFeatures = JSONObject.parseObject(salesPlanSDO.getFeatures(), SalesPlanFeatures.class);
                BeanUtils.copyProperties(salesPlanFeatures, salesPlanSDO);
            }
            // 状态
            salesPlanSDO.setStatusDesc(SalesPlanStatusEnum.getDesc(salesPlanSDO.getStatus()));
            // 计划时间
            if (StringUtil.isNotEmpty(salesPlanSDO.getPlanTime())) {
                String planTime = DateUtils.stampToDate(salesPlanSDO.getPlanTime());
                try {
                    //2021年10月份
                    salesPlanSDO.setFormatPlanTime(DateUtils.formatPlanTime(planTime));
                    //2021-10-01 00:00:00
                    salesPlanSDO.setPlanTime(planTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // 编辑按钮
            if (SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus())) {
                salesPlanSDO.setIsEdit(false);
            } else {
                salesPlanSDO.setIsEdit(true);
            }
            // 删除按钮
//            if (SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus()) && planDetailCountMap.get(salesPlanSDO.getId()) == null){
//                salesPlanSDO.setIsDelete(true);
//            }else{
//                salesPlanSDO.setIsDelete(false);
//            }
            // 发布按钮
            boolean isPublish = true;
            if (SalesPlanModelEnum.PLAN_MODEL.getModel().equals(salesPlanSDO.getModel())) {
                if (salesPlanSDO.getStatus() >= SalesPlanStatusEnum.TO_BE_PUBLISHED.getCode()) {
                    isPublish = false;
                }
            } else {
                if (salesPlanSDO.getStatus() >= SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getCode() || salesPlanSDO.getStatus().equals(SalesPlanStatusEnum.PUBLISHED.getCode())) {
                    isPublish = false;
                }
            }
            salesPlanSDO.setIsPublish(isPublish);

            //20240516 一盘货上线后,调整由总部发起
            salesPlanSDO.setIsAdjust(true);
//            // 调整按钮
//            if (SalesPlanStatusEnum.PUBLISHED.getCode().equals(salesPlanSDO.getStatus())) {
//                salesPlanSDO.setIsAdjust(false);
//            } else {
//                salesPlanSDO.setIsAdjust(true);
//            }

            // 审批状态
            if (pageQuerySalePlanRequest.getBizType() != null && StringUtil.isNotEmpty(pageQuerySalePlanRequest.getBizId())) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(pageQuerySalePlanRequest.getBizType());
                if (byOrganizationType == null) {
                    throw new FacadeException("OTS-02-002-02-15-007");
                }
                SalesPlanReportQueryRequest salesPlanReportQueryRequest = new SalesPlanReportQueryRequest();
                salesPlanReportQueryRequest.setModelId(salesPlanSDO.getId().toString());
                salesPlanReportQueryRequest.setModelType(salesPlanSDO.getModel());
                salesPlanReportQueryRequest.setBizId(pageQuerySalePlanRequest.getBizId());
                salesPlanReportQueryRequest.setBizType(byOrganizationType.getBizType());
                Result<SalesPlanReportSDO> salesPlanReportSDOResult = salesPlanReportQueryService.querySalesPlanReport(salesPlanReportQueryRequest);
                if (null != salesPlanReportSDOResult && null != salesPlanReportSDOResult.getResult()) {
                    salesPlanSDO.setAuditStatus(salesPlanReportSDOResult.getResult().getAuditStatus());
                    salesPlanSDO.setAuditStatusName(
                        SalesPlanReportAuditStatusEnum.of(salesPlanReportSDOResult.getResult().getAuditStatus()).getDesc());
                    salesPlanSDO.setReportStatus(salesPlanReportSDOResult.getResult().getStatus());
                    salesPlanSDO.setReportStatusName(
                        SalesPlanReportStatusEnum.of(salesPlanReportSDOResult.getResult().getStatus()).getDesc());
                    salesPlanSDO.setReportId(salesPlanReportSDOResult.getResult().getId());
                } else {
                    salesPlanSDO.setAuditStatus(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode());
                    salesPlanSDO.setAuditStatusName(SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getDesc());
                    salesPlanSDO.setReportStatus(SalesPlanReportStatusEnum.TO_REPORT.getCode());
                    salesPlanSDO.setReportStatusName(SalesPlanReportStatusEnum.TO_REPORT.getDesc());
                }
            }
            salesPlanSDO.setStatusInfo(getStatusDesc(salesPlanSDO.getStatus() == null ? null : salesPlanSDO.getStatus()));
            //业务状态=待锁定状态且审批状态等于待提交；展示处理按钮
            if (SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus())
                   /* && SalesPlanReportAuditStatusEnum.TO_BE_REVIEW.getCode() == salesPlanSDO.getAuditStatus()*/) {
                salesPlanSDO.setIsAudit(false);
            } else {
                salesPlanSDO.setIsAudit(true);
            }
            // 总经理特判
//            if (roles.stream().anyMatch(roleSDO -> RoleCodeEnum.GENERAL_MANAGER.getCode().equals(roleSDO.getCode()))) {
//                if (SalesPlanStatusEnum.TO_BE_LOCKED.getCode() == salesPlanSDO.getStatus()
//                        && SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode() == salesPlanSDO.getAuditStatus()) {
//                    salesPlanSDO.setIsAudit(false);
//                }
//            }
        });
    }

    public static com.alibaba.fastjson.JSONObject getStatusDesc(Integer type) {
        if (type == null)
            return null;
        if (type == SalesPlanStatusEnum.TO_BE_LOCKED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_LOCKED.getDesc(), "success");
        } else if (type == SalesPlanStatusEnum.TO_BE_SYNC.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_SYNC.getDesc(), "warning");
        } else if (type == SalesPlanStatusEnum.TO_BE_REPLIED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_REPLIED.getDesc(), "error");
        } else if (type == SalesPlanStatusEnum.TO_BE_PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.TO_BE_PUBLISHED.getDesc(), "warning");
        } else if (type == SalesPlanStatusEnum.PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.PUBLISHED.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.ADJUST.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUST.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUSTED_TO_BE_REPLIED.getDesc(), "success");
        } else if (type == SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getCode()) {
            return generateStatus(SalesPlanStatusEnum.ADJUSTED_TO_BE_PUBLISHED.getDesc(), "middle");
        } else if (type == SalesPlanStatusEnum.CANCEL.getCode()) {
            return generateStatus(SalesPlanStatusEnum.CANCEL.getDesc(), "cancel");
        }
        return null;
    }

    public static com.alibaba.fastjson.JSONObject generateStatus(String msg, String color) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("text", msg);
        obj.put("type", color);
        return obj;
    }

    @Override
    @FacadeInvoker
    public Result<SalesPlanSDO> loadLatelySalesPlan(QuerySalesPlanRequest querySalesPlanRequest) {
        SalesPlanSDO planSDO = salesPlanRepository.loadLatelySalesPlan(querySalesPlanRequest);
        return Result.success(planSDO);
    }

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanSDO>> loadLatelySalesPlans(QuerySalesPlanRequest querySalesPlanRequest) {
        List<SalesPlanSDO> salesPlanSDOList = salesPlanRepository.loadLatelySalesPlans(querySalesPlanRequest);
        return Result.success(salesPlanSDOList);
    }

    @Override
    @FacadeInvoker
    public Result<List<OrganizationSDO>> organizationSelect(OrganizationSelectRequest organizationSelectRequest) {
        List<OrganizationSDO> organizationSDOList = new ArrayList<>();
        if (OrganizationTypeEnum.COMPANY.getCode() < Integer.valueOf(organizationSelectRequest.getRelatedOrganizationType())) {
            //登录人的角色小于分子公司的,需要层级往上找
            IdQueryRequest idQueryRequest = IdQueryRequest.newIdQueryRequestBuilder()
                    .id(organizationSelectRequest.getRelatedOrganizationId())
                    .type(OrganizationTypeEnum.COMPANY.getCode())
                    .build();
            Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> topOrgList = organizationQueryService.getTopOrganizationList(idQueryRequest);
            if (null != topOrgList && null != topOrgList.getResult() && CollectionUtils.isNotEmpty(topOrgList.getResult())) {
                topOrgList.getResult().forEach(x -> {
                    if (OrganizationTypeEnum.COMPANY.getCode().equals(x.getType())) {
                        OrganizationSDO organizationSDO = new OrganizationSDO();
                        BeanUtils.copyProperties(x, organizationSDO);
                        organizationSDOList.add(organizationSDO);
                    }
                });
            }
        } else if (OrganizationTypeEnum.COMPANY.getCode() == Integer.valueOf(organizationSelectRequest.getRelatedOrganizationType())) {
            //登录人为分子公司那一层，直接根据id查询名称
            BaselineGetOrganizationByIdsRequest baselineGetOrganizationByIdsRequest = BaselineGetOrganizationByIdsRequest.builder()
                    .ids(Lists.newArrayList(organizationSelectRequest.getRelatedOrganizationId()))
                    .build();
            Object response = baseDataService.baselineGetOrganizationByIds(baselineGetOrganizationByIdsRequest);
            if (Objects.nonNull(response)) {
                buildResponse(response, organizationSDOList);
            }
        } else if (OrganizationTypeEnum.COMPANY.getCode() > Integer.valueOf(organizationSelectRequest.getRelatedOrganizationType())) {
            //登录人大于分子分子公司级别，查询查询所有的业务单元
//            BaselineGetOrganizationByTypeRequest baselineGetOrganizationByTypeRequest = BaselineGetOrganizationByTypeRequest.builder()
//                    .type(OrganizationTypeEnum.COMPANY.getCode().toString())
//                    .build();
//            Object response = baseDataService.baselineGetOrganizationByType(baselineGetOrganizationByTypeRequest);
//            if (Objects.nonNull(response)) {
//                buildResponse(response, organizationSDOList);
//            }
            GetOrganizationByTypeResponse response = organizationQueryService.getOrganizationByType(GetOrganizationByTypeRequest.builder().type(OrganizationTypeEnum.COMPANY.getCode().toString()).build());
            if (null != response.getResult() && null != response.getResult() && CollectionUtils.isNotEmpty(response.getResult())) {
                response.getResult().forEach(x -> {
                    if (OrganizationTypeEnum.COMPANY.getCode().equals(x.getType())) {
                        OrganizationSDO organizationSDO = new OrganizationSDO();
                        BeanUtils.copyProperties(x, organizationSDO);
                        organizationSDOList.add(organizationSDO);
                    }
                });
            }
        }
        return Result.success(organizationSDOList);
    }

    private void buildResponse(Object response, List<OrganizationSDO> organizationSDOList) {
        Map saleMap = (Map) response;
        JSONArray result = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(saleMap)).getJSONArray("result");
        if (CollectionUtils.isNotEmpty(result)) {
            for (int i = 0; i < result.size(); i++) {
                OrganizationSDO sdo = new OrganizationSDO();
                com.alibaba.fastjson.JSONObject organizationSDO = result.getJSONObject(i).getJSONObject("organizationSDO");
                String id = Optional.ofNullable(organizationSDO.getString("id")).orElse(null);
                String name = Optional.ofNullable(organizationSDO.getString("name")).orElse(null);
                sdo.setId(id);
                sdo.setName(name);
                organizationSDOList.add(sdo);
            }
        }
    }
}
